#include "mainwindow.hpp"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton_10,SIGNAL(clicked()), this, SLOT(showAddLabelDialog()));
    connect(ui->actionAdd_User_Style, SIGNAL(triggered()), this, SLOT(showNewStyleDialog()));

    QString styleFile;
    styleFile = QDir::homePath() + "/.XViz/rsc/style.xml";

    XMLReader reader;
    reader.read(styleFile.toAscii().data());
    bs = ChartStyleFactory::Instance().CreateBibStyle();

    QString temp;

    for(unsigned int i=0; i<bs->_styles.size(); ++i)
        ui->comboBox_3->addItem(temp.setNum(bs->_styles[i]->_StyleID));

    this->labels = new Labels();
    this->labels->_Output = "X11";
}

MainWindow::~MainWindow()
{
    delete ui;
    //    if(this->wlabels)
    //        delete wlabels;
    //delete labels;

    for(unsigned int i=0; i<this->ListOfCharts.size(); ++i)
        delete this->ListOfCharts[i];

    if(QFile::exists(QDir::homePath()+"/.XViz/plot.gplt"))
        QFile::remove(QDir::homePath()+"/.XViz/plot.gplt");
    if(QFile::exists(QDir::homePath()+"/.XViz/data.xviz"))
        QFile::remove(QDir::homePath()+"/.XViz/data.xviz");
}

void MainWindow::on_comboBox_activated(int index)
{
    ui->tableWidget->clearContents();
    QStringList ns;
    for(unsigned int i=0; i<ZbiorDanych->_DataSplitted[index]._Data.size(); ++i)
    {
        QString str = QString::fromStdString(ZbiorDanych->_DataSplitted[index]._Data[i]);
        str.remove(QChar('\r'));
        ns = str.split("   ");
        for(int j=0; j<ns.count(); ++j){
            QTableWidgetItem *temp = new QTableWidgetItem(ns.at(j));
            ui->tableWidget->setItem(i,j,temp);
        }
    }

    QString textOut;
    QString str_col;
    QString str_row;
    QString str_minX;
    QString str_minY;
    QString str_minZ;
    QString str_maxX;
    QString str_maxY;
    QString str_maxZ;
    str_col.setNum(this->ZbiorDanych->numOfCols(index));
    str_row.setNum(this->ZbiorDanych->numOfRows(index));
    str_minX.setNum(this->ZbiorDanych->minInCol(index,0));
    str_maxX.setNum(this->ZbiorDanych->maxInCol(index,0));
    str_minY.setNum(this->ZbiorDanych->minInCol(index,1));
    str_maxY.setNum(this->ZbiorDanych->maxInCol(index,1));

    textOut += ("Column numbers: " + str_col +"\n");
    textOut += ("Row numbers: " + str_row + "\n");
    textOut += ("Min X: " + str_minX + "\n");
    textOut += ("Max X: " + str_maxX + "\n");
    textOut += ("Min Y: " + str_minY + "\n");
    textOut += ("Max Y: " + str_maxY + "\n");

    if(ns.count() == 3)
    {
        str_minZ.setNum(this->ZbiorDanych->minInCol(index,2));
        textOut += ("Min Z: " + str_minZ + "\n");
        str_maxZ.setNum(this->ZbiorDanych->maxInCol(index,2));
        textOut += ("Max Z: " + str_maxZ + "\n");
    }


    ui->textEdit_2->setText(textOut);

}

void MainWindow::showAddLabelDialog()
{
    wlabels = new SetLabels(this);
    wlabels->setWindowTitle("Set Chart Labels");
    wlabels->show();
    emit this->sendChartConf(labels);
}

void MainWindow::showNewStyleDialog()
{
    wstyle = new NewStyle(this);
    wstyle->setWindowTitle("Add User Style");
    wstyle->show();
}

void MainWindow::on_pushButton_5_clicked() //add
{
    Graph *Chart = new Graph();

    int nr = ui->comboBox->currentIndex();
    this->labels->_Title = (ui->comboBox->itemText(nr).toAscii().data());

    int nr2 = ui->comboBox_3->currentIndex();
    Chart->setStyle(ui->comboBox_3->itemText(nr2).toInt());
    this->ListOfCharts.push_back(Chart);

    QListWidgetItem *Item = new QListWidgetItem();
    Item->setText(QString::fromStdString(this->labels->_Title));
    ui->listWidget->addItem(Item);
    ui->listWidget->setCurrentRow(ui->listWidget->count()-1);

    if(this->ListOfCharts.size()>0){
        ui->pushButton_8->setEnabled(1);
    }

    if(this->ListOfCharts[this->ListOfCharts.size()-1]->getifLine() == 1)
        ui->checkBox->setCheckState(Qt::Checked);
    else
        ui->checkBox->setCheckState(Qt::Unchecked);

}


void MainWindow::on_pushButton_6_clicked() //remove
{
    if(this->ListOfCharts.size()>0){
        int nr = ui->listWidget->row(ui->listWidget->currentItem());
        if(this->ListOfCharts.size()>1)
            this->ListOfCharts.erase(ListOfCharts.begin()+nr);
        else
            this->ListOfCharts.pop_back(); // DO POPRAWIENIA!
        ui->listWidget->takeItem(nr);

        //QString title = ui->lineEdit->text();
        //this->labels->_Title = title.toAscii().data();

        if(this->ListOfCharts.size()==0){
            ui->pushButton_8->setEnabled(0);
        }
    }
}

void MainWindow::on_listWidget_clicked(QModelIndex index)
{
    int nr = index.row();

    if(ui->listWidget->item(nr)->text().size()<5)
    {
        int set = ui->listWidget->item(nr)->text().toInt()-1;
        this->on_comboBox_activated(set);
        ui->comboBox_3->setCurrentIndex(this->ListOfCharts[nr]->getStyle()-1);
    }
    else{
        QStringList name = ui->listWidget->item(nr)->text().split(" ");
        ui->comboBox_3->setCurrentIndex(this->ListOfCharts[nr]->getStyle()-1);
    }

    if(this->ListOfCharts[nr]->getifLine() == 1)
        ui->checkBox->setCheckState(Qt::Checked);
    else
        ui->checkBox->setCheckState(Qt::Unchecked);
}

void MainWindow::getChartConf(Labels* lab)
{
    this->labels = lab;
}

void MainWindow::getNewStyle(ChartStyle *st)
{
    int nr = this->bs->_styles.size();
    st->_StyleID = nr+1;
    ChartStyleFactory::Instance().addStyle(st->_StyleID,"1",st->_LineColor,st->_LineWidth, st->_PointType,st->_PointSize,"1");
    bs = ChartStyleFactory::Instance().CreateBibStyle();

    QString temp;
    nr = this->bs->_styles.size();
    ui->comboBox_3->addItem(temp.setNum(bs->_styles[nr-1]->_StyleID));

    XMLWriter writer;
    writer.write(QDir::homePath() + "/.XViz/style.xml", this->bs);

}

void MainWindow::on_pushButton_11_clicked()
{
    int index = this->ui->comboBox->currentIndex();
    vector<string> tempData = this->ZbiorDanych->_DataSplitted[index]._Data;
    QString Output;
    vector<float> processedData;
    processedData.clear();
    this->ui->checkBox_2->setEnabled(1);

    QString str = QString::fromStdString(tempData[0]);
    QStringList ns = str.split("   ");

    if(ns.count()<=2){
        if(this->ui->comboBox_2->currentText()=="Linear Regression"){
            processedData = this->ZbiorDanych->linearRegression(tempData);
            QString a,b;
            a = a.setNum(processedData[0]);
            b = b.setNum(processedData[1]);
            Output += "Estimators for f(x)=ax+b: \n";
            Output += ("a = " + a + "\n");
            Output += ("b = " + b + "\n");
        }
        else if(this->ui->comboBox_2->currentText()=="Quadratic Regression"){
            processedData = this->ZbiorDanych->quadraticRegression(tempData);
            QString a,b,c;
            a = a.setNum(processedData[0]);
            b = b.setNum(processedData[1]);
            c = c.setNum(processedData[2]);
            Output += "Estimators for f(x)=ax^2+bx+c: \n";
            Output += ("a = " + a + "\n");
            Output += ("b = " + b + "\n");
            Output += ("c = " + c + "\n");
        }
        this->ui->checkBox_2->setChecked(1);
    }
    else
    {
        Output += "Data set contains to much variables, to use linear or quadratic regression choose only two.";
        this->ui->checkBox_2->setEnabled(0);
    }
    this->ui->textEdit->setText(Output);


    if(ns.count()<=2){
        QStringList labels;
        labels << "X" << "Y" << "estimator Y";
        this->ui->tableWidget->setHorizontalHeaderLabels(labels);

        double estY;
        double x;
        QString str_estY;
        for(unsigned int i=0; i<tempData.size(); ++i){
            x = ui->tableWidget->item(i,0)->text().toDouble();
            if(this->ui->comboBox_2->currentText()=="Linear Regression")
                estY = processedData[0]*x + processedData[1];
            else
                estY = processedData[0]*x*x + processedData[1]*x + processedData[2];
            str_estY.setNum(estY);
            QTableWidgetItem *temp = new QTableWidgetItem(str_estY);
            ui->tableWidget->setItem(i,2,temp);
        }
    }

    if(ui->checkBox_2->isChecked())
    {
        //utworzenie kontenera z obrobionymi danymi
        QString str_x;
        QString str_esty;
        QString outLine;
        Set tempSet;
        for(unsigned int i=0; i<tempData.size(); ++i){
            str_x = ui->tableWidget->item(i,0)->text();
            str_esty = ui->tableWidget->item(i,2)->text();
            outLine = str_x + "   " + str_esty;
            tempSet._Data.push_back(outLine.toAscii().data());
        }
        tempSet._Top.push_back("# Dane z obróbki");
        this->ZbiorDanych->_DataProcessed.push_back(tempSet);

        Graph* Chart = new Graph();
        Chart->setStyle(1);
        this->ListOfCharts.push_back(Chart);

        QListWidgetItem *Item = new QListWidgetItem();
        Item->setText(QString::fromStdString(this->labels->_Title) + " processed");
        ui->listWidget->addItem(Item);
        ui->listWidget->setCurrentRow(ui->listWidget->count()-1);
    }
}

void MainWindow::on_pushButton_8_clicked() //plot
{
    QStringList ns;
    vector<int> listID;
    for(unsigned int i=0; i<this->ListOfCharts.size(); ++i){
        if(ui->listWidget->item(i)->text().size()<5)
            listID.push_back(ui->listWidget->item(i)->text().toInt()-1);
        ns = QString::fromStdString(this->ZbiorDanych->_DataSplitted[ui->listWidget->item(i)->text().toInt()-1]._Data[0]).split("   ");
        if(ns.count()==2)
            this->ListOfCharts[i]->setSize(2);
        else if(ns.count()==3)
            this->ListOfCharts[i]->setSize(3);
    }

    if(this->labels->_Output == "postscript eps" ||
       this->labels->_Output == "latex"){
        QString file2SaveName = QFileDialog::getSaveFileName(this, tr("Save File"),"",
                                                             tr("Files (*.*)"));
        this->labels->_OutputFileName = file2SaveName.toAscii().data();
    }

    ZbiorDanych->generateDataFile(listID);

    ZbiorDanych->generateScriptFile(bs,this->ListOfCharts,labels);

    QString program = "gnuplot";
    QStringList arguments;
    arguments << "-persist" << (QDir::homePath()+"/.XViz/plot.gplt");

    QProcess myProcess;

    myProcess.startDetached(program, arguments);
}

void MainWindow::on_actionOpen_file_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"",
                                                    tr("Files (*.dat)"));
    if(fileName!=""){
        ZbiorDanych = new Data();

        QByteArray   bytes  = fileName.toAscii();
        char * ptr    = bytes.data();

        ZbiorDanych->setFileName(ptr);
        ZbiorDanych->ReadData();
        ZbiorDanych->SplitData();

        QString temp;


        for(unsigned int i=1; i<=ZbiorDanych->_DataSplitted.size(); ++i)
            ui->comboBox->addItem(temp.setNum(i));

        //poprawić poniższy warunek w pętli
        for(unsigned int i=0; i<ZbiorDanych->_DataSplitted[0]._Data.size(); ++i)
        {
            QString str = QString::fromStdString(ZbiorDanych->_DataSplitted[0]._Data[i]);
            str.remove(QChar('\r'));
            QStringList ns = str.split("   ");
            for(int j=0; j<ns.count(); ++j){
                QTableWidgetItem *tempItem = new QTableWidgetItem(ns.at(j));
                ui->tableWidget->setItem(i,j,tempItem);
            }
        }
    }
}

void MainWindow::on_actionExit_triggered()
{
    unsigned int ret = QMessageBox::question(this, "Are you sure?",
                                             "Do you really want to close XViz \n and lose all your data?",
                                             QMessageBox::Yes | QMessageBox::No);
    if(ret & QMessageBox::Yes)
        this->close();
}

void MainWindow::on_comboBox_3_activated(int index)
{
    if(this->ListOfCharts.size()>0){
        int SetNr = ui->listWidget->currentRow();
        this->ListOfCharts[SetNr]->setStyle(index+1);
    }
}

void MainWindow::on_checkBox_clicked()
{
    int SetNr = ui->listWidget->currentRow();
    if(ui->checkBox->isChecked())
        this->ListOfCharts[SetNr]->setifLine(1);
    else
        this->ListOfCharts[SetNr]->setifLine(0);
}

void MainWindow::on_comboBox_4_activated(int index)
{
    string Out = ui->comboBox_4->itemText(index).toAscii().data();
    if(Out == "X11")
        this->labels->_Output = "X11";
    else if(Out == "EPS")
        this->labels->_Output = "postscript eps";
    else if(Out == "LaTeX")
        this->labels->_Output = "latex";
}

void MainWindow::on_actionAbout_XViz_triggered()
{
    QString text;
    text += "<I></I><center>Universal program  <br>";
    text += "for data processing & wisualization.<br><br>";
    text += "Wroclaw University of Technology<br>";
    text += "Faculty of Electronics<br>";
    text += "2011<br><br>";
    text += "Author: Karol Kurpanik<br>";
    text += "Control Engineering & Robotics, ARR</center>";

    QMessageBox::about(this,"About",text);
}

void MainWindow::on_actionUser_Manual_triggered()
{
    QUrl url;
    url.setUrl(QDir::homePath() + "/.XViz/rsc/instr.pdf");
    QDesktopServices::openUrl(url);
}

void MainWindow::on_pushButton_9_clicked() //reset
{
    ui->listWidget->clear();
    this->ListOfCharts.clear();
    ui->pushButton_8->setDisabled(1);
    this->labels->clearLabel();
}

void MainWindow::on_actionNew_Library_triggered()
{
    ChartStyleFactory::Instance().remStyles();
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"",
                                                    tr("Files (*.xml)"));
    ui->comboBox_3->clear();

    XMLReader reader;
    reader.read(fileName);

    bs = ChartStyleFactory::Instance().CreateBibStyle();

    QString temp;

    for(unsigned int i=0; i<bs->_styles.size(); ++i)
        ui->comboBox_3->addItem(temp.setNum(bs->_styles[i]->_StyleID));
}
